import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService, NzModalService, NzUploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
import { RechargeService } from 'src/app/service/recharge.service';
import { API_CONFIG } from 'src/app/service/service.module';

@Component({
  selector: 'app-offline-pay',
  templateUrl: './offline-pay.component.html',
  styleUrls: ['./offline-pay.component.less']
})
export class OfflinePayComponent implements OnInit {

  validateForm!: FormGroup;
  payImages: string | null;
  payImageUrl?: string;
  loading: boolean = false;
  uploadUrl: string | null = '';
  headers: any | null = null;

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('必须上传一张图片!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片必须小于2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.payImages = info.file.response.name;
        this.payImageUrl = info.file.response.url;
        this.loading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status == "VALID") {
      var data = this.validateForm.value;
      data['type'] = '转账汇款';
      if (this.payImages)
        data['payImages'] = this.payImages;
      this.rechargeService.save(data).subscribe(result => {
        this.validateForm.reset();
        for (const key in this.validateForm.controls) {
          this.validateForm.controls[key].markAsPristine();
          this.validateForm.controls[key].updateValueAndValidity();
        }
        this.modalService.success({
          nzTitle: '信息提示',
          nzContent: '转账汇款登记成功，请等待财务人员审核!'
        });
      });
    }
  }

  constructor(
    private fb: FormBuilder,
    private modalService: NzModalService,
    private rechargeService: RechargeService,
    private msg: NzMessageService,
    @Inject(API_CONFIG) private uri: string
  ) { }

  ngOnInit(): void {
    this.uploadUrl = this.uri + '/custom/upload/transfer-capture';
    let ticket = window.sessionStorage['ticket'];
    this.headers = { 'Authorization': 'BasicAuth ' + ticket };
    this.validateForm = this.fb.group({
      amount: [null, [Validators.required, Validators.pattern(/^(0|[1-9]\d*)(\.\d{1,2})?$/)]],
      payAccountName: [null, [Validators.required, Validators.pattern(/^[\u4e00-\u9fa5]+$/)]],
      payAccountNo: [null, [Validators.required, Validators.pattern(/^\d{15,22}$/)]],
    });
  }

}
